'''
Created on Apr 25, 2012

@author: root
'''

# This class represents an individual hadoop configuration File
#import wx
from Base import Base
from xml.etree.ElementTree import parse
import Queue
#import threading
#import shutil

#import datetime

class XML_File(Base):
   
    goldDir = ""
    goldFilename = ""
    configDir = ""
    goldPath = ""
    remoteDir = "/usr/lib/gphd/hadoop/conf/"
    Nodes = []
    Log = []
    Users = []
    returnQueue = Queue.Queue()
    Properties = []
    xmlTree = None
    xmlFile = None
   
   
   
   
    def AddProperty(self,nvArray):
        self.xmlFile = open(self.goldPath,'a')
        
        for pair in nvArray:
            self.xmlFile.write("<property>\n")
            self.xmlFile.write("<name>"+str(pair['name'])+"</name>\n"    )
            self.xmlFile.write("<value>"+str(pair['value'])+"</value>\n"    )
            self.xmlFile.write("</property>\n")

        self.xmlFile.close()
        
    def GetValue(self,propName):
        
        valueFound =  False
        for element in self.xmlTree.findall('property'):
            nameFound = False
            for child in element.getchildren():
                prop = {}
                if (str(child.text).upper() == str(propName).upper()):
                    nameFound = True
                elif  (str(child.tag).upper() == 'VALUE') and (nameFound):
                    return (True,child.text)
        return (False,"PROPERTY NAME NOT FOUND")
                
      

        
        
                
    def Modify(self,mod_propName,mod_propValue):
        '''
        This method modifies the local Gold Copy of the XML file that was used to instantiate the
        Object.  It will modify the value of the given Property Name.   It writes the new
        version of the Gold file and copies he old file out to the "previous" directory
        '''       
           
        prevValue = 0
        self.xmlFile = open(self.goldPath,'r')
        for element in self.xmlTree.findall('property'):
            nameFound = False
            for child in element.getchildren():
                prop = {}
                if (str(child.text).upper() == str(mod_propName).upper()):
                    nameFound = True
                elif  (str(child.tag).upper() == 'VALUE') and (nameFound):
                    nameFound = False
                    prevValue = child.text
                    child.text = mod_propValue
        try:
            self.xmlTree.write(self.goldPath)
            self.LogInfo("Changed "+str(mod_propName) + " from " + str(prevValue) + " to " + str(mod_propValue))
        except Exception,err:
            self.LogError("Error Setting "+str(mod_propName)+" to "+str(mod_propValue)+":"+str(err))
        self.xmlFile.close()



    def Write(self):
        
        try:
            baseFileHandle = open (self.configDir+ "/gold/hadoop/base-site.xml","r")
            goldFileHandle = open (self.goldPath,"r")
            baseData = baseFileHandle.read()
            goldData = goldFileHandle.read()
            goldFileHandle.close()
        except Exception,err:
            self.LogError("Error Reading Base XML and Gold XML:"+str(err))
        try:
            new_goldFileHandle = open(self.goldPath,"w")
            new_goldFileHandle.write(baseData+"\n")      
            new_goldFileHandle.write(goldData)
            new_goldFileHandle.close()      
            self.LogInfo("Saved new Gold XML File"+":"+str(self.xmlFilename)+":Success")
            print "        * Saved Modified Copy of "+ str(self.xmlFilename)
            baseFileHandle.close()
            return 0

        except Exception,err:
            self.LogError("Could Not Save New Version of "+ str(self.xmlFilename)+":"+str(err))
            print "        * ERROR: Could Not Save New Version of "+ str(self.xmlFilename())
            return -1
                   
    def Parse(self):
        """
        Parsese XML Config file into Element tree and pulls
        out the name,value pairs
        """
        print "    * Parsing Existing "+ self.xmlFilename
        try:
            self.xmlFile = open(self.goldPath,'r')
            self.xmlTree = parse(self.xmlFile)
            self.Properties = []
            for element in self.xmlTree.findall('property'):
                nameFound = False
                for child in element.getchildren():
                    prop = {}
                    if (str(child.tag).upper() == 'NAME'):
                        nameFound = True
                        propName = child.text
                    elif  (str(child.tag).upper() == 'VALUE') and (nameFound):
                        nameFound = False
                        propValue = child.text
                        prop['name'] = propName
                        prop['value'] = propValue
                        self.Properties.append(prop)
                        self.LogInfo(str(self.xmlFilename) + " : Current : "+str(propName)+" : "+str(propValue))
            return 0
            self.xmlFile.close()

        except Exception, err:
            self.LogError(err)
            return -1
            
   

    def __init__(self,configDir, xmlFilename):

       
        Base.__init__(self)
        self.configDir = configDir
        self.xmlFilename = xmlFilename
        self.goldPath = self.configDir+ "/gold/hadoop/" + self.xmlFilename
        self.previousPath = self.configDir + "/previous/hadoop/" + self.xmlFilename
        self.Parse()
    
